package com.foxconn.ipebg.common.base.util;




import ipebg.mzk.common.util.PropertyPhase;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.io.FilenameUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.exception.FdfsUnsupportStorePathException;
import com.github.tobato.fastdfs.service.FastFileStorageClient;

@Component
public class FastDFSClientWrapper {

	private static Log log = LogFactory.getLog(FastDFSClientWrapper.class);

    @Autowired
    private FastFileStorageClient storageClient;


    /**
     * 上传文件
     * @param file 文件对象
     * @return 文件访问地址
     * @throws IOException
     */
    public StorePath uploadFile(MultipartFile file) throws IOException {
        StorePath storePath = storageClient.uploadFile(file.getInputStream(),file.getSize(), FilenameUtils.getExtension(file.getOriginalFilename()),null);
        return storePath;
    }

    /**
     * 将一段字符串生成一个文件上传
     * @param content 文件内容
     * @param fileExtension
     * @return
     */
    public StorePath uploadFile(String content, String fileExtension) {
        byte[] buff = content.getBytes(Charset.forName("UTF-8"));
        ByteArrayInputStream stream = new ByteArrayInputStream(buff);
        StorePath storePath = storageClient.uploadFile(stream,buff.length, fileExtension,null);
        return storePath;
    }

    // 封装图片完整URL地址
    public String getResAccessUrl(StorePath storePath) {
    	String filePrefix=PropertyPhase.readData("FASTDFS_HTTP_PREFIX");
        String fileUrl = filePrefix + storePath.getFullPath();
        return fileUrl;
    }

    /**
     * 删除文件
     * @param fileUrl 文件访问地址
     * @return
     */
    public void deleteFile(StorePath storePath) {
        try {
            storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
        } catch (FdfsUnsupportStorePathException e) {
            log.error(e.getMessage());
        }
    }
    
    /**
     * 删除文件
     * @param fileUrl 文件访问地址
     * @return
     */
    public void batchDeleteFile(List<StorePath> storePathList) {
        try {
        	if(storePathList==null||storePathList.size()==0){
        		return;
        	}
        	Iterator it=storePathList.iterator();
        	StorePath storePath;
        	while(it.hasNext()){
        		storePath=(StorePath)it.next();
        		storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
        	}
            
        } catch (FdfsUnsupportStorePathException e) {
            log.error(e.getMessage());
            throw e;
        }
    }
    
}